/**
 * 使用form-data格式发送http请求
 *
 *
 */

import React from "react"
import { getRootUrl } from "./environment";
import { isEmpty } from "../utils/cmn";
import Cache from "../utils/Cache";
import fetch from 'isomorphic-fetch'
import {URL} from "./enum";

const generateUrl = (url) => {
	return getRootUrl() + String(url)
}

// post按form data格式整合参数
const generatePostData = data => {
	let formData = new FormData();
	for (let k in data) {
		formData.append(k, data[k]);
	}
	return formData;
}

// post
const basePost = (url, postData) => {
	url  = generateUrl(url);
	// 生成options
	let userInfo = Cache.getUserInfo();
	// 生成options
	let options = {method: 'post'}
	if (!isEmpty(userInfo)) {
		options.headers = {"Authorization": userInfo.key};
	}
	// 生成body
	if (!isEmpty(postData)) {
		options.body = generatePostData(postData);
	}
	const promiseObj = fetch(url, options);
	return promiseObj.then(
		resolve => {
			return resolve
		},
		reject => {
			return reject
		}
	)
}

export const Post = (url, postData= {}) => {
	return basePost(url, postData).then(
		response => {
			if (!response || response.status !== 200) {
				return {code: 1, msg: "请求错误"}
			}
			if(!response.jsonData)
				response.jsonData = response.json()
			return response.jsonData
		}
	).then(
		json => {
			return json
		}
	)
}


// put
const basePut = (url, postData) => {
	url  = generateUrl(url);
	// 生成options
	let userInfo = Cache.getUserInfo();
	// 生成options
	let options = {method: 'put'}
	if (!isEmpty(userInfo)) {
		options.headers = {"Authorization": userInfo.key};
	}
	// 生成body
	if (!isEmpty(postData)) {
		options.body = generatePostData(postData);
	}
	const promiseObj = fetch(url, options);
	return promiseObj.then(
		resolve => {
			return resolve
		},
		reject => {
			return reject
		}
	)
}

export const Put = (url, postData= {}) => {
	return basePut(url, postData).then(
		response => {
			if (!response || response.status !== 200) {
				return {code: 1, msg: "请求错误"}
			}
			if(!response.jsonData)
				response.jsonData = response.json()
			return response.jsonData
		}
	).then(
		json => {
			return json
		}
	)
}

export const Url = URL;
